//
//  MGReceiptController.m
//  MoneyRecord_iOS
//
//  Created by alchemy on 2022/1/7.
//

#import "MGRecordController.h"
#import "MGAlertViewController.h"

#import "MGBaseActionsView.h"

#import "MGCreateDateCell.h"
#import "MGCreateMoneyCell.h"
#import "MGBaseBorderDetailCell.h"
#import "MGBaseBorderInputCell.h"

#import "MGAlertManager.h"

@interface MGRecordController ()
@property (nonatomic, strong) MGBaseActionsView *actionsView;

@end

@implementation MGRecordController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = APP_COLOR_BACKGROUND;
    self.tableView.backgroundColor = [UIColor clearColor];
    
    if (self.updateModel) {
        self.dataModel = [MGRecordModel yy_modelWithJSON:self.updateModel.yy_modelToJSONObject];
    } else {
        self.dataModel = [[MGRecordModel alloc] init];
        self.dataModel.recordType = self.recordType;
    }
}

- (void)afterConfigViewAction {
    [super afterConfigViewAction];
    
    @weakify(self);
    self.actionsView = [MGBaseActionsView createViewAtSuperView:self.view constraintBlock:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.view);
        make.height.mas_equalTo(65 + [UIDevice safeAreaInsetsBottom]);
    } configureBlock:^(MGBaseActionsView *view) {
        view.createBlock = ^{
            @strongify(self);
            [self createRecordAction];
        };
        view.updateBlock = ^{
            @strongify(self);
            [self updateRecordAction];
        };
        view.deleteBlock = ^{
            @strongify(self);
            if (self.updateModel.uniqueId == UNIQUE_ID_CANUPLOAD) {
                [YYBAlertView showAlertViewWithStatusString:@"默认账本不可删除"];
            } else {
                [self deleteRecordAction];
            }
        };
    }];
    
    if (self.updateModel) {
        [self.actionsView changeUpdate];
    } else {
        [self.actionsView changeCompleteCreate];
    }
    
    if (self.updateModel.uniqueId == UNIQUE_ID_CANUPLOAD) {
        // 默认账本不可删除
        [self.actionsView.secondActionButton setTitleColor:YYBCOLOR(0xD5D2D2) forState:0];
    }
}

- (void)deleteRecordAction {
    @weakify(self);
    [MGAlertView showAlertViewWithTitle:@"确定删除吗?" detail:@"所有数据也会被删除并且不可恢复。" firstActionTitle:@"取消" firstActionTapedBlock:^{
        
    } secondActionTitle:@"确定删除" secondActionTapedBlock:^{
        @strongify(self);
        [self _deleteRecordAction];
    }];
}

- (void)_deleteRecordAction {
    if ([MGOssManager shouldUpload]) {
        self.refreshAlertView = [MGAlertView showLoadingWithString:@"正在删除" inView:self.view];
    }
    
    @weakify(self);
    [MGRecordAccessor.shared deleteDataModel:self.updateModel completeBlock:^{
        @strongify(self);
        self.deleteRecordModelBlock();
        [MGAlertView closeAlertView:self.refreshAlertView showString:@"删除成功"];
        [self.navigationController popViewControllerAnimated:YES];
    } errorBlock:^(NSError *error) {
        @strongify(self);
        [MGAlertView closeAlertView:self.refreshAlertView showError:error];
    }];
}

// 更新小目标
- (void)updateRecordAction {
    if (!self.dataModel.name.isExist ||
        self.dataModel.name.length > 8) {
        [YYBAlertView showAlertViewWithStatusString:@"请输入8个字符及以内的名称"];
    } else {
        if ([MGOssManager shouldUpload]) {
            self.refreshAlertView = [MGAlertView showLoadingWithString:@"正在更新" inView:self.view];
        }
        @weakify(self);
        [MGRecordAccessor.shared updateDataModel:self.updateModel shouldUpdateModel:self.dataModel completeBlock:^{
            @strongify(self);
            [MGAlertView closeAlertView:self.refreshAlertView showString:@"更新成功"];
//            [MGAlertManager createAlert:self.updateModel completeBlock:nil];
            self.updateRecordModelBlock();
            [self.navigationController popViewControllerAnimated:YES];
        } errorBlock:^(NSError *error) {
            @strongify(self);
            [MGAlertView closeAlertView:self.refreshAlertView showError:error];
        }];
    }
}

// 创建小目标
- (void)createRecordAction {
    if (!self.dataModel.name.isExist ||
        self.dataModel.name.length > 8) {
        [YYBAlertView showAlertViewWithStatusString:@"请输入8个字符及以内的名称"];
    } else {
        if ([MGOssManager shouldUpload]) {
            self.refreshAlertView = [MGAlertView showLoadingWithString:@"正在添加" inView:self.view];
        }
        @weakify(self);
        [MGRecordAccessor.shared createDataModel:self.dataModel completeBlock:^{
            @strongify(self);
            if (self.dataModel.recordType == MGRecordType365Money) {
                [self.dataModel createRecordProject];
            }
            
            [MGAlertView closeAlertView:self.refreshAlertView showString:@"添加成功"];
            [MGAlertManager createAlert:self.dataModel completeBlock:nil];
            self.createRecordModelBlock();
            [self.navigationController popViewControllerAnimated:YES];
        } errorBlock:^(NSError *error) {
            @strongify(self);
            [MGAlertView closeAlertView:self.refreshAlertView showError:error];
        }];
    }
}

// 修改提醒内容
- (void)alertActionHandler {
    @weakify(self);
    [YYBViewRouter openOnClass:[MGAlertViewController class] configureBlock:^(MGAlertViewController *obj) {
        @strongify(self);
        obj.updateModel = self.dataModel.alertModel;
        obj.updateAlertModelBlock = ^(MGAlertModel * _Nonnull dataModel) {
            self.dataModel.alertModel = dataModel;
            [self.tableView reloadData];
        };
    }];
}

- (NSArray<NSString *> *)dequeueCellIdentifiers {
    return @[@"MGCreateDateCell", @"MGCreateMoneyCell", @"MGBaseBorderDetailCell",
    @"MGBaseBorderInputCell"];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        if (self.recordType == MGRecordTypeNormal) {
            return 1;
        }
        return 4;
    } else if (section == 1) {
        return 1;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1) {
        return 60;
    }
    return 50;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    @weakify(self);
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            MGBaseBorderInputCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MGBaseBorderInputCell"];
            cell.stringChangedBlock = ^(NSString *text) {
                @strongify(self);
                self.dataModel.name = text;
            };
            
            cell.inputStringView.keyboardType = UIKeyboardTypeDefault;
            [cell configViewWithCornerType:self.recordType == MGRecordTypeNormal ? MGCornerTypeAll : MGCornerTypeTop];
            [cell configViewWithTitleValue:@"账本名称" detailValue:self.dataModel.name iconName:@"cell_name"];
            return cell;
        } else if (indexPath.row == 1) {
            MGCreateMoneyCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MGCreateMoneyCell"];
            cell.stringChangedBlock = ^(NSString *text) {
                @strongify(self);
                self.dataModel.gapMoney = text.floatValue;
            };
            
            [cell configViewWithCornerType:MGCornerTypeCenter];
            [cell configViewWithMoney:self.dataModel.gapMoney];
            return cell;
        } else if (indexPath.row == 2) {
            MGCreateDateCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MGCreateDateCell"];
            
            [cell configViewWithCornerType:MGCornerTypeCenter];
            [cell configViewWithDate:self.dataModel.startDate];
            return cell;
        } else if (indexPath.row == 3) {
            MGBaseBorderInputCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MGBaseBorderInputCell"];
            cell.stringChangedBlock = ^(NSString *text) {
                @strongify(self);
                self.dataModel.lastDays = text.integerValue;
            };
            
            cell.inputStringView.keyboardType = UIKeyboardTypeNumberPad;
            [cell configViewWithCornerType:MGCornerTypeBottom];
            [cell configViewWithTitleValue:@"持续时间" detailValue:@(self.dataModel.lastDays).stringValue iconName:@"cell_days"];
            return cell;
        }
    } else if (indexPath.section == 1) {
        MGBaseBorderDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MGBaseBorderDetailCell"];
        
        [cell configViewWithCornerType:MGCornerTypeAll];
        [cell configViewWithTitleValue:@"提醒通知" detailValue:[self.dataModel.alertModel getAlertType] iconName:@"cell_alert"];
        return cell;
    }
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    @weakify(self);
    if (indexPath.section == 0) {
        // 设置日期
        if (indexPath.row == 2) {
            [YYBAlertView showDatePickerAlertViewWithSelectedBlock:^(NSDate * _Nonnull selectedDate) {
                @strongify(self);
                self.dataModel.startDate = selectedDate;
                [self.tableView reloadRowAtIndexPath:indexPath withRowAnimation:UITableViewRowAnimationNone];
            } mode:UIDatePickerModeDate date:self.dataModel.startDate];
        }
    } else if (indexPath.section == 1) {
        [self alertActionHandler];
    }
}

- (NSString *)customPageTitle {
    if (self.updateModel) {
        return @"修改账本";
    } else {
        return @"添加账本";
    }
}

- (UIEdgeInsets)handleEdgeInsets {
    UIEdgeInsets insets = [super handleEdgeInsets];
    insets.top += 10;
    return insets;
}

@end
